package com.ran.gpstestbed;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;

public class TerminalFragment extends Fragment implements ServiceConnection, SerialListener {

    private enum Connected { False, Pending, True }

    private String deviceAddress;
    private com.ran.gpstestbed.SerialService service;

    private TextView receiveText;
    private TextView sendText;
    private com.ran.gpstestbed.TextUtil.HexWatcher hexWatcher;

    private Connected connected = Connected.False;
    private boolean initialStart = true;
    private boolean hexEnabled = false;
    private boolean pendingNewline = false;
    private String newline = com.ran.gpstestbed.TextUtil.newline_crlf;


    private TextView displaydata1;
    private TextView displaydata2;
    private TextView displaydata3;
    private TextView displaydata4;
    private TextView displaydata5;
    private TextView displaydata6;
    private TextView displaydata7;
    private TextView displaydata8;
    private TextView displaydata9;
    private TextView displaydata10;
    private TextView displaydata11;
    private TextView displaydata12;
    private TextView displaydata13;
    private TextView displaydata14;
    private TextView displaydata15;
    private TextView displaydata16;
    private TextView displaydata17;
    private TextView displaydata18;
    private TextView displaydata19;
    private TextView displaydata20;
    private TextView displaydata21;
    private TextView displaydata22;
    private TextView displaydata23;
    private TextView displaydata24;
    private TextView displaydata25;
    private TextView displaydata26;
    private TextView displaydata27;





    private MapView mMapView;
    private BaiduMap mBaiduMap;   // 定义百度地图对象
    private LocationClient mLocationClient;  //定义LocationClient
    private BDLocationListener myListener = new MyLocationListener();  //定义位置监听
    private boolean isFirstLoc = true;  //定义第一次启动
    private MyLocationConfiguration.LocationMode mCurrentMode;  //定义当前定位模式
    private BitmapDescriptor mBitmapDescriptorStart;
    private BitmapDescriptor mBitmapDescriptorStart1;
    private BitmapDescriptor mBitmapDescriptorStart2;
    private Marker mMarker;




    /*
     * Lifecycle
     */
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        setRetainInstance(true);
        deviceAddress = getArguments().getString("device");






    }

    @Override
    public void onDestroy() {
        if (connected != Connected.False)
            disconnect();
        getActivity().stopService(new Intent(getActivity(), com.ran.gpstestbed.SerialService.class));
        super.onDestroy();

        /*新加的*/
        mMapView.onDestroy();
        mMapView=null;
    }

    @Override
    public void onStart() {
        super.onStart();
        if(service != null)
            service.attach(this);
        else
            getActivity().startService(new Intent(getActivity(), com.ran.gpstestbed.SerialService.class)); // prevents service destroy on unbind from recreated activity caused by orientation change

        mBaiduMap.setMyLocationEnabled(true);
        mLocationClient.start();
    }

    @Override
    public void onStop() {
        if(service != null && !getActivity().isChangingConfigurations())
            service.detach();
        super.onStop();

        mBaiduMap.setMyLocationEnabled(false);
        mLocationClient.stop();
    }

    @SuppressWarnings("deprecation") // onAttach(context) was added with API 23. onAttach(activity) works for all API versions
    @Override
    public void onAttach(@NonNull Activity activity) {
        super.onAttach(activity);
        getActivity().bindService(new Intent(getActivity(), com.ran.gpstestbed.SerialService.class), this, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onDetach() {
        try { getActivity().unbindService(this); } catch(Exception ignored) {}
        super.onDetach();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(initialStart && service != null) {
            initialStart = false;
            getActivity().runOnUiThread(this::connect);
        }

    /*新加的*/
        mMapView.onResume();
    }

    /*新加的*/
    @Override
    public void onPause(){
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        service = ((com.ran.gpstestbed.SerialService.SerialBinder) binder).getService();
        service.attach(this);
        if(initialStart && isResumed()) {
            initialStart = false;
            getActivity().runOnUiThread(this::connect);
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        service = null;
    }

    @Override
    public void onNullBinding(ComponentName name) {
        ServiceConnection.super.onNullBinding(name);
    }

    /*
     * UI
     */
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_terminal, container, false);

        /*
        新加的
        */

        TabHost tabHost=view.findViewById(android.R.id.tabhost);
        tabHost.setup();
        LayoutInflater inflater1=LayoutInflater.from(getContext());
        inflater1.inflate(R.layout.tab1,tabHost.getTabContentView());
        inflater1.inflate(R.layout.tab2,tabHost.getTabContentView());
        inflater1.inflate(R.layout.tab3,tabHost.getTabContentView());
        inflater1.inflate(R.layout.tab4,tabHost.getTabContentView());
        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("MAP").setContent(R.id.left));
        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("FORM").setContent(R.id.middle));
        tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("MSG").setContent(R.id.middle2));
        tabHost.addTab(tabHost.newTabSpec("tab4").setIndicator("ABOUT").setContent(R.id.right));


        receiveText = view.findViewById(R.id.receive_text);                          // TextView performance decreases with number of spans
        receiveText.setTextColor(getResources().getColor(R.color.colorRecieveText)); // set as default color to reduce number of spans
        receiveText.setMovementMethod(ScrollingMovementMethod.getInstance());




        SDKInitializer.initialize(getContext());
        //自4.3.0起，百度地图SDK所有接口均支持百度坐标和国测局坐标，用此方法设置您使用的坐标类型.
        //包括BD09LL和GCJ02两种坐标，默认是BD09LL坐标。
        SDKInitializer.setCoordType(CoordType.BD09LL);
        mMapView= view.findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();  //获取百度地图对象

        mLocationClient = new LocationClient(getContext());  //创建LocationClient类
        mLocationClient.registerLocationListener(myListener);   //注册监听函数
        mBitmapDescriptorStart = BitmapDescriptorFactory.fromResource(R.drawable.icon_binding_point);
        mBitmapDescriptorStart1 = BitmapDescriptorFactory.fromResource(R.drawable.icon_mark);
        mBitmapDescriptorStart2 = BitmapDescriptorFactory.fromResource(R.drawable.water_drop);
        initLocation();  //调用initLocation()方法，实现初始化定位


        Button button=view.findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //输入经纬度并转化为Double
                EditText wd=view.findViewById(R.id.PosW);
                wd.getText();
                String str1 = wd.getText().toString();
                Double wd1 = Double.parseDouble(str1);
                EditText jd=view.findViewById(R.id.PosJ);
                jd.getText();
                String str2 = jd.getText().toString();
                Double jd1 = Double.parseDouble(str2);



                //手动标点
                LatLng center = new LatLng(wd1, jd1);
                MarkerOptions markerOptions = new MarkerOptions()
                        .position(center)
                        .icon(mBitmapDescriptorStart)
                        .visible(true);
                mMarker = (Marker) mBaiduMap.addOverlay(markerOptions);


            }
        });


        /*0415做按钮*/

        Button button2=view.findViewById(R.id.btmarksingle);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Layout layout = receiveText.getLayout();
                String text = receiveText.getText().toString();

                int line = layout.getLineCount();

                /*经度*/
                int linej=line-23;
                int start1=layout.getLineStart(linej);
                int end1= layout.getLineEnd(linej);
                String text1=text.substring(start1,end1-3);

                /*纬度*/
                int linew=line-22;
                int start2=layout.getLineStart(linew);
                int end2= layout.getLineEnd(linew);
                String text2=text.substring(start2,end2-3);


                Log.d("MyText1View", "jd " + text1);
                Log.d("MyText2View", "wd " + text2);

                Double jd2 = Double.parseDouble(text1);
                Double wd2 = Double.parseDouble(text2);


                LatLng center = new LatLng(wd2, jd2);
                MarkerOptions markerOptions = new MarkerOptions()
                        .position(center)
                        .icon(mBitmapDescriptorStart1);
                mMarker = (Marker) mBaiduMap.addOverlay(markerOptions);


            }
        });


        Button button3=view.findViewById(R.id.btmarkcontinue);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                EditText times=view.findViewById(R.id.marknum);
                times.getText();
                String strtimes = times.getText().toString();
                int inttime = Integer.parseInt(strtimes);

                for (int countt=1;countt<=inttime;countt++){

                    Layout layoutco = receiveText.getLayout();
                    String textco = receiveText.getText().toString();

                    int lineco = layoutco.getLineCount();

                    /*经度*/
                    int linejco=lineco-23;
                    int start1co=layoutco.getLineStart(linejco);
                    int end1co= layoutco.getLineEnd(linejco);
                    String text1co=textco.substring(start1co,end1co-3);

                    /*纬度*/
                    int linewco=lineco-23;
                    int start2co=layoutco.getLineStart(linewco);
                    int end2co= layoutco.getLineEnd(linewco);
                    String text2co=textco.substring(start2co,end2co-3);


                    Log.d("MyText1View", "jd " + text1co);
                    Log.d("MyText2View", "wd " + text2co);

                    Double jd2co = Double.parseDouble(text1co);
                    Double wd2co = Double.parseDouble(text2co);


                    LatLng centerco = new LatLng(wd2co, jd2co);
                    MarkerOptions markerOptionsco = new MarkerOptions()
                            .position(centerco)
                            .icon(mBitmapDescriptorStart2);
                    mMarker = (Marker) mBaiduMap.addOverlay(markerOptionsco);




                }





            }
        });




        Button buttontab3clr=view.findViewById(R.id.tab3clr);
        buttontab3clr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                receiveText.setText("");
            }
        });



        displaydata1 = view.findViewById(R.id.tab2lon);
        displaydata2 = view.findViewById(R.id.tab2lat);
        displaydata3 = view.findViewById(R.id.tab2id1);
        displaydata4 = view.findViewById(R.id.tab2si1);
        displaydata5 = view.findViewById(R.id.tab2po11);
        displaydata6 = view.findViewById(R.id.tab2po12);
        displaydata7 = view.findViewById(R.id.tab2po13);
        displaydata8 = view.findViewById(R.id.tab2id2);
        displaydata9 = view.findViewById(R.id.tab2si2);
        displaydata10 = view.findViewById(R.id.tab2po21);
        displaydata11 = view.findViewById(R.id.tab2po22);
        displaydata12 = view.findViewById(R.id.tab2po23);
        displaydata13 = view.findViewById(R.id.tab2id3);
        displaydata14 = view.findViewById(R.id.tab2si3);
        displaydata15 = view.findViewById(R.id.tab2po31);
        displaydata16 = view.findViewById(R.id.tab2po32);
        displaydata17 = view.findViewById(R.id.tab2po33);
        displaydata18 = view.findViewById(R.id.tab2id4);
        displaydata19 = view.findViewById(R.id.tab2si4);
        displaydata20 = view.findViewById(R.id.tab2po41);
        displaydata21 = view.findViewById(R.id.tab2po42);
        displaydata22 = view.findViewById(R.id.tab2po43);
        displaydata23 = view.findViewById(R.id.tab2id5);
        displaydata24 = view.findViewById(R.id.tab2si5);
        displaydata25 = view.findViewById(R.id.tab2po51);
        displaydata26 = view.findViewById(R.id.tab2po52);
        displaydata27 = view.findViewById(R.id.tab2po53);


        Button buttontab2clr=view.findViewById(R.id.tab2clr);
        buttontab2clr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                displaydata1.setText("");
                displaydata2.setText("");
                displaydata3.setText("");
                displaydata4.setText("");
                displaydata5.setText("");
                displaydata6.setText("");
                displaydata7.setText("");
                displaydata8.setText("");
                displaydata9.setText("");
                displaydata10.setText("");
                displaydata11.setText("");
                displaydata12.setText("");
                displaydata13.setText("");
                displaydata14.setText("");
                displaydata15.setText("");
                displaydata16.setText("");
                displaydata17.setText("");
                displaydata18.setText("");
                displaydata19.setText("");
                displaydata20.setText("");
                displaydata21.setText("");
                displaydata23.setText("");
                displaydata24.setText("");
                displaydata25.setText("");
                displaydata26.setText("");
                displaydata27.setText("");


            }
        });












        Button buttontab2get=view.findViewById(R.id.tab2get);
        buttontab2get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Layout layout = receiveText.getLayout();
                String text = receiveText.getText().toString();

                int line = layout.getLineCount();
                int n = 0 ;

                /*经度*/
                int linej=41;
                int start1=layout.getLineStart(linej);
                int end1= layout.getLineEnd(linej);
                String text1=text.substring(start1,end1-3);

                /*纬度*/
                int linew=42;
                int start2=layout.getLineStart(linew);
                int end2= layout.getLineEnd(linew);
                String text2=text.substring(start2,end2-3);

                int lineid1=1 + n ;
                int start3=layout.getLineStart(lineid1);
                int end3= layout.getLineEnd(lineid1);
                String text3=text.substring(start3,end3-3);

                int linesi1= 5 + n ;
                int start4=layout.getLineStart(linesi1);
                int end4= layout.getLineEnd(linesi1);
                String text4=text.substring(start4,end4-3);

                int linepo11= 6 + n;
                int start5=layout.getLineStart(linepo11);
                int end5= layout.getLineEnd(linepo11);
                String text5=text.substring(start5,end5-3);

                int linepo12= 7 + n;
                int start6=layout.getLineStart(linepo12);
                int end6= layout.getLineEnd(linepo12);
                String text6=text.substring(start6,end6-3);

                int linepo13= 8 + n;
                int start7=layout.getLineStart(linepo13);
                int end7= layout.getLineEnd(linepo13);
                String text7=text.substring(start7,end7-3);

                n += 8 ;

                int lineid2= 1 + n;
                int start8=layout.getLineStart(lineid2);
                int end8= layout.getLineEnd(lineid2);
                String text8=text.substring(start8,end8-3);

                int linesi2= 5 + n;
                int start9=layout.getLineStart(linesi2);
                int end9= layout.getLineEnd(linesi2);
                String text9=text.substring(start9,end9-3);

                int linepo21= 6 + n;
                int start10=layout.getLineStart(linepo21);
                int end10= layout.getLineEnd(linepo21);
                String text10=text.substring(start10,end10-3);

                int linepo22= 7 + n;
                int start11=layout.getLineStart(linepo22);
                int end11= layout.getLineEnd(linepo22);
                String text11=text.substring(start11,end11-3);

                int linepo23= 8 + n;
                int start12=layout.getLineStart(linepo23);
                int end12= layout.getLineEnd(linepo23);
                String text12=text.substring(start12,end12-3);

                n += 8 ;

                int lineid3= 1 + n;
                int start13=layout.getLineStart(lineid3);
                int end13= layout.getLineEnd(lineid3);
                String text13=text.substring(start13,end13-3);

                int linesi3= 5 + n;
                int start14=layout.getLineStart(linesi3);
                int end14= layout.getLineEnd(linesi3);
                String text14=text.substring(start14,end14-3);

                int linepo31= 6 + n;
                int start15=layout.getLineStart(linepo31);
                int end15= layout.getLineEnd(linepo31);
                String text15=text.substring(start15,end15-3);

                int linepo32= 7 + n;
                int start16=layout.getLineStart(linepo32);
                int end16= layout.getLineEnd(linepo32);
                String text16=text.substring(start16,end16-3);

                int linepo33= 8 + n;
                int start17=layout.getLineStart(linepo33);
                int end17= layout.getLineEnd(linepo33);
                String text17=text.substring(start17,end17-3);

                n += 8 ;

                int lineid4= 1 + n;
                int start18=layout.getLineStart(lineid4);
                int end18= layout.getLineEnd(lineid4);
                String text18=text.substring(start18,end18-3);

                int linesi4= 5 + n ;
                int start19=layout.getLineStart(linesi4);
                int end19= layout.getLineEnd(linesi4);
                String text19=text.substring(start19,end19-3);

                int linepo41= 6 + n;
                int start20=layout.getLineStart(linepo41);
                int end20= layout.getLineEnd(linepo41);
                String text20=text.substring(start20,end20-3);

                int linepo42= 7 + n;
                int start21=layout.getLineStart(linepo42);
                int end21= layout.getLineEnd(linepo42);
                String text21=text.substring(start21,end21-3);

                int linepo43= 8 + n;
                int start22=layout.getLineStart(linepo43);
                int end22= layout.getLineEnd(linepo43);
                String text22=text.substring(start22,end22-3);

                n += 8 ;

                int lineid5= 1 + n;
                int start23=layout.getLineStart(lineid5);
                int end23= layout.getLineEnd(lineid5);
                String text23=text.substring(start23,end23-3);

                int linesi5= 5 + n ;
                int start24=layout.getLineStart(linesi5);
                int end24= layout.getLineEnd(linesi5);
                String text24=text.substring(start24,end24-3);

                int linepo51= 6 + n;
                int start25=layout.getLineStart(linepo51);
                int end25= layout.getLineEnd(linepo51);
                String text25=text.substring(start25,end25-3);

                int linepo52= 7 + n;
                int start26=layout.getLineStart(linepo52);
                int end26= layout.getLineEnd(linepo52);
                String text26=text.substring(start26,end26-3);

                int linepo53= 8 + n;
                int start27=layout.getLineStart(linepo53);
                int end27= layout.getLineEnd(linepo53);
                String text27=text.substring(start27,end27-3);


                displaydata1.setText(text1);
                displaydata2.setText(text2);
                displaydata3.setText(text3);
                displaydata4.setText(text4);
                displaydata5.setText(text5);
                displaydata6.setText(text6);
                displaydata7.setText(text7);
                displaydata8.setText(text8);
                displaydata9.setText(text9);
                displaydata10.setText(text10);
                displaydata11.setText(text11);
                displaydata12.setText(text12);
                displaydata13.setText(text13);
                displaydata14.setText(text14);
                displaydata15.setText(text15);
                displaydata16.setText(text16);
                displaydata17.setText(text17);
                displaydata18.setText(text18);
                displaydata19.setText(text19);
                displaydata20.setText(text20);
                displaydata21.setText(text21);
                displaydata23.setText(text23);
                displaydata24.setText(text24);
                displaydata25.setText(text25);
                displaydata26.setText(text26);
                displaydata27.setText(text27);


            }
        });




        Button buttontab2grp=view.findViewById(R.id.tab2grp);
        buttontab2grp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                Context context = getView().getContext();
                intent.setClass(context,Graph1.class);
                Bundle bundle = new Bundle();
                bundle.putString("tab2lon", String.valueOf(displaydata1));
                bundle.putString("tab2lat", String.valueOf(displaydata2));
                bundle.putString("tab2id1", String.valueOf(displaydata3));
                bundle.putString("tab2si1", String.valueOf(displaydata4));
                bundle.putString("tab2po11", String.valueOf(displaydata5));
                bundle.putString("tab2po12", String.valueOf(displaydata6));
                bundle.putString("tab2po13", String.valueOf(displaydata7));
                bundle.putString("tab2id2", String.valueOf(displaydata8));
                bundle.putString("tab2si2", String.valueOf(displaydata9));
                bundle.putString("tab2po21", String.valueOf(displaydata10));
                bundle.putString("tab2po22", String.valueOf(displaydata11));
                bundle.putString("tab2po23", String.valueOf(displaydata12));
                bundle.putString("tab2id3", String.valueOf(displaydata13));
                bundle.putString("tab2si3", String.valueOf(displaydata14));
                bundle.putString("tab2po31", String.valueOf(displaydata15));
                bundle.putString("tab2po32", String.valueOf(displaydata16));
                bundle.putString("tab2po33", String.valueOf(displaydata17));
                bundle.putString("tab2id4", String.valueOf(displaydata18));
                bundle.putString("tab2si4", String.valueOf(displaydata19));
                bundle.putString("tab2po41", String.valueOf(displaydata20));
                bundle.putString("tab2po42", String.valueOf(displaydata21));
                bundle.putString("tab2po43", String.valueOf(displaydata22));
                bundle.putString("tab2id5", String.valueOf(displaydata23));
                bundle.putString("tab2si5", String.valueOf(displaydata24));
                bundle.putString("tab2po51", String.valueOf(displaydata25));
                bundle.putString("tab2po52", String.valueOf(displaydata26));
                bundle.putString("tab2po53", String.valueOf(displaydata27));

                bundle.putInt("height", 175);
                intent.putExtras(bundle);

                startActivity(intent);


            }
        });






        sendText = view.findViewById(R.id.send_text);
        hexWatcher = new com.ran.gpstestbed.TextUtil.HexWatcher(sendText);
        hexWatcher.enable(hexEnabled);
        sendText.addTextChangedListener(hexWatcher);
        sendText.setHint(hexEnabled ? "HEX mode" : "");

        View sendBtn = view.findViewById(R.id.send_btn);
        sendBtn.setOnClickListener(v -> send(sendText.getText().toString()));
        return view;
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_terminal, menu);
        menu.findItem(R.id.hex).setChecked(hexEnabled);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.clear) {
            receiveText.setText("");
            return true;
        } else if (id == R.id.newline) {
            String[] newlineNames = getResources().getStringArray(R.array.newline_names);
            String[] newlineValues = getResources().getStringArray(R.array.newline_values);
            int pos = java.util.Arrays.asList(newlineValues).indexOf(newline);
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("Newline");
            builder.setSingleChoiceItems(newlineNames, pos, (dialog, item1) -> {
                newline = newlineValues[item1];
                dialog.dismiss();
            });
            builder.create().show();
            return true;
        } else if (id == R.id.hex) {
            hexEnabled = !hexEnabled;
            sendText.setText("");
            hexWatcher.enable(hexEnabled);
            sendText.setHint(hexEnabled ? "HEX mode" : "");
            item.setChecked(hexEnabled);
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    /*
     * Serial + UI
     */
    private void connect() {
        try {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
            status("Connecting...");
            connected = Connected.Pending;
            com.ran.gpstestbed.SerialSocket socket = new com.ran.gpstestbed.SerialSocket(getActivity().getApplicationContext(), device);
            service.connect(socket);
        } catch (Exception e) {
            onSerialConnectError(e);
        }
    }

    private void disconnect() {
        connected = Connected.False;
        service.disconnect();
    }

    private void send(String str) {
        if(connected != Connected.True) {
            Toast.makeText(getActivity(), "not connected", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            String msg;
            byte[] data;
            if(hexEnabled) {
                StringBuilder sb = new StringBuilder();
                com.ran.gpstestbed.TextUtil.toHexString(sb, com.ran.gpstestbed.TextUtil.fromHexString(str));
                com.ran.gpstestbed.TextUtil.toHexString(sb, newline.getBytes());
                msg = sb.toString();
                data = com.ran.gpstestbed.TextUtil.fromHexString(msg);
            } else {
                msg = str;
                data = (str + newline).getBytes();
            }
            SpannableStringBuilder spn = new SpannableStringBuilder(msg + '\n');
            spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorSendText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            receiveText.append(spn);
            service.write(data);
        } catch (Exception e) {
            onSerialIoError(e);
        }
    }

    private void receive(byte[] data) {
        if(hexEnabled) {
            receiveText.append(com.ran.gpstestbed.TextUtil.toHexString(data) + '\n');
        } else {
            String msg = new String(data);
            if(newline.equals(com.ran.gpstestbed.TextUtil.newline_crlf) && msg.length() > 0) {
                // don't show CR as ^M if directly before LF
                msg = msg.replace(com.ran.gpstestbed.TextUtil.newline_crlf, com.ran.gpstestbed.TextUtil.newline_lf);
                // special handling if CR and LF come in separate fragments
                if (pendingNewline && msg.charAt(0) == '\n') {
                    Editable edt = receiveText.getEditableText();
                    if (edt != null && edt.length() > 1)
                        edt.replace(edt.length() - 2, edt.length(), "");
                }
                pendingNewline = msg.charAt(msg.length() - 1) == '\r';
            }
            receiveText.append(com.ran.gpstestbed.TextUtil.toCaretString(msg, newline.length() != 0));
        }
    }

    private void status(String str) {
        SpannableStringBuilder spn = new SpannableStringBuilder(str + '\n');
        spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorStatusText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        receiveText.append(spn);
    }

    /*
     * SerialListener
     */
    @Override
    public void onSerialConnect() {
        status("Connect to 'H-C-2010-06-01' successfully");
        connected = Connected.True;
    }

    @Override
    public void onSerialConnectError(Exception e) {
        status("connection failed: " + e.getMessage());
        disconnect();
    }

    @Override
    public void onSerialRead(byte[] data) {
        receive(data);
    }

    @Override
    public void onSerialIoError(Exception e) {
        status("connection lost: " + e.getMessage());
        disconnect();
    }

    /*新加的*/
    private void initLocation() {  //该方法实现初始化定位
        //创建LocationClientOption对象，用于设置定位方式
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll");  //设置坐标类型
        option.setScanSpan(1000);      //1秒定位一次
        option.setOpenGps(true);      //打开GPS
        mLocationClient.setLocOption(option);  //保存定位参数与信息
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;  //设置定位模式
        //设置自定义定位图标
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                .fromResource(R.drawable.icon_trans);
        //位置构造方式，将定位模式，定义图标添加其中
        MyLocationConfiguration config = new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker);
        mBaiduMap.setMyLocationConfigeration(config);  //地图显示定位图标
    }

    public class MyLocationListener implements BDLocationListener {  //设置定位监听器
        @Override
        public void onReceiveLocation(BDLocation location) {
            //销毁后不再处理新接收的位置
            if (location == null || mMapView == null)
                return;
            // 构造定位数据
            MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100)
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude())
                    .build();
            // 设置定位数据
            mBaiduMap.setMyLocationData(locData);

            if (isFirstLoc) {  //如果是第一次定位,就定位到以自己为中心
                LatLng ll = new LatLng(location.getLatitude(), location.getLongitude()); //获取用户当前经纬度
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);  //更新坐标位置
                mBaiduMap.animateMapStatus(u);                            //设置地图位置
                isFirstLoc = false;                                      //取消第一次定位
            }

        }
    }
}
